<template>
  <view class="container">
    <view class="header">
      <text class="title">收益统计</text>
    </view>
    
    <!-- 收益概览卡片 -->
    <view class="stats-grid">
      <view class="stats-item">
        <text class="stats-label">昨日收益</text>
        <text class="stats-value">¥{{ yesterdayEarnings }}</text>
      </view>
      <view class="stats-item">
        <text class="stats-label">本月收益</text>
        <text class="stats-value">¥{{ monthEarnings }}</text>
      </view>
      <view class="stats-item">
        <text class="stats-label">累计收益</text>
        <text class="stats-value">¥{{ totalEarnings }}</text>
      </view>
    </view>
    
    <!-- 日期筛选 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">筛选条件</text>
      </view>
      <view class="date-filter">
        <view class="filter-item">
          <text class="filter-label">开始日期</text>
          <picker mode="date" :value="startDate" @change="onStartDateChange">
            <view class="date-picker">{{ startDate || '请选择' }}</view>
          </picker>
        </view>
        <view class="filter-item">
          <text class="filter-label">结束日期</text>
          <picker mode="date" :value="endDate" @change="onEndDateChange">
            <view class="date-picker">{{ endDate || '请选择' }}</view>
          </picker>
        </view>
        <button class="search-btn" @click="searchEarnings">查询</button>
      </view>
    </view>
    
    <!-- 收益列表 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">收益明细</text>
      </view>
      <view v-if="earningsList.length === 0" class="empty-state">
        <image src="/static/images/noData.png" class="empty-img" />
        <text class="empty-text">暂无收益记录</text>
      </view>
      <view v-else class="earnings-list">
        <view v-for="item in earningsList" :key="item.id" class="earnings-item">
          <view class="item-info">
            <text class="date">{{ item.earningDate }}</text>
            <text class="orders">完成订单：{{ item.totalOrders }}单</text>
          </view>
          <view class="item-amount">
            <text class="amount">¥{{ item.totalEarnings }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 加载更多 -->
    <view v-if="hasMore" class="load-more" @click="loadMore">
      <text class="load-text">{{ loading ? '加载中...' : '加载更多' }}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import { getYesterdayEarnings, getTotalEarnings, getEarningsStatistics, getEarningsRecords } from '@/api/earnings'

const userStore = useUserStore()

// 统计数据
const yesterdayEarnings = ref('0.00')
const monthEarnings = ref('0.00')
const totalEarnings = ref('0.00')

// 筛选条件
const startDate = ref('')
const endDate = ref('')

// 列表数据
const earningsList = ref([])
const loading = ref(false)
const hasMore = ref(true)
const pageNo = ref(1)
const pageSize = 20

// 初始化日期（默认查询最近30天）
const initDates = () => {
  const today = new Date()
  const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000)
  
  endDate.value = today.toISOString().split('T')[0]
  startDate.value = thirtyDaysAgo.toISOString().split('T')[0]
}

// 加载统计数据
const loadStatsData = async () => {
  try {
    if (!userStore.merchantId) return
    
    const [yesterdayRes, totalRes] = await Promise.all([
      getYesterdayEarnings(userStore.merchantId),
      getTotalEarnings(userStore.merchantId)
    ])
    
    yesterdayEarnings.value = yesterdayRes.data || '0.00'
    totalEarnings.value = totalRes.data || '0.00'
    
    // 获取收益统计数据（包含本月收益）
    const statsRes = await getEarningsStatistics(userStore.merchantId)
    if (statsRes.data) {
      monthEarnings.value = statsRes.data.monthEarnings || '0.00'
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    uni.showToast({ title: '加载数据失败', icon: 'none' })
  }
}

// 加载收益列表
const loadEarningsList = async (reset = false) => {
  if (loading.value) return
  
  try {
    loading.value = true
    
    if (reset) {
      pageNo.value = 1
      earningsList.value = []
      hasMore.value = true
    }
    
    const params = {
      merchantId: userStore.merchantId,
      startDate: startDate.value,
      endDate: endDate.value,
      pageNo: pageNo.value,
      pageSize
    }
    
    const {data} = await getEarningsRecords(params)
    
    if (data?.list) {
      if (reset) {
        earningsList.value = data.list
      } else {
        earningsList.value.push(...data.list)
      }
      
      hasMore.value = earningsList.value.length < data.total
      if (data.list.length > 0) {
        pageNo.value++
      }
    }
  } catch (error) {
    console.error('加载收益列表失败:', error)
    uni.showToast({ title: '加载列表失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 日期选择
const onStartDateChange = (e) => {
  startDate.value = e.detail.value
}

const onEndDateChange = (e) => {
  endDate.value = e.detail.value
}

// 查询收益
const searchEarnings = () => {
  if (!startDate.value || !endDate.value) {
    uni.showToast({ title: '请选择查询日期', icon: 'none' })
    return
  }
  
  if (new Date(startDate.value) > new Date(endDate.value)) {
    uni.showToast({ title: '开始日期不能大于结束日期', icon: 'none' })
    return
  }
  
  loadEarningsList(true)
}

// 加载更多
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    loadEarningsList()
  }
}



onMounted(async () => {
  initDates()
  await loadStatsData()
  await loadEarningsList(true)
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

/* 收益概览卡片 */
.stats-grid {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 24rpx;
  margin: 32rpx 0 40rpx 0;
}

.stats-item {
  flex: 1;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 24rpx 0 rgba(0,0,0,0.06);
  padding: 36rpx 0 32rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: box-shadow 0.2s;
}

.stats-label {
  font-size: 26rpx;
  color: #888;
  margin-bottom: 10rpx;
  letter-spacing: 1rpx;
}

.stats-value {
  font-size: 40rpx;
  font-weight: bold;
  color: #ff6b6b;
  margin-bottom: 0;
}

/* 筛选区域 */
.section {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 30rpx;
}

.section-header {
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.date-filter {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 30rpx;
}

.filter-label {
  font-size: 28rpx;
  color: #666;
  width: 120rpx;
  flex-shrink: 0;
}

.date-picker {
  flex: 1;
  padding: 24rpx 30rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
  min-width: 300rpx;
  background-color: #fafafa;
  transition: border-color 0.2s;
}

.date-picker:active {
  border-color: #ff6b6b;
}

.search-btn {
  background: linear-gradient(to right, #ff9a9e, #ff6b6b);
  color: #fff;
  border: none;
  border-radius: 12rpx;
  padding: 24rpx 60rpx;
  font-size: 30rpx;
  font-weight: bold;
  margin-top: 20rpx;
  width: 100%;
  box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.3);
  transition: transform 0.2s;
}

.search-btn:active {
  transform: scale(0.98);
}

/* 收益列表 */
.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-img {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.earnings-list {
  margin-top: 20rpx;
}

.earnings-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.earnings-item:last-child {
  border-bottom: none;
}

.item-info {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.date {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.orders {
  font-size: 26rpx;
  color: #666;
}

.item-amount {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 10rpx;
}

.amount {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff6b6b;
}



/* 加载更多 */
.load-more {
  text-align: center;
  padding: 40rpx 0;
  background: #fff;
  border-radius: 16rpx;
  margin-top: 20rpx;
}

.load-text {
  font-size: 28rpx;
  color: #666;
}
</style>